10303. Harmonic series
For a given
value of n, compute the sum of the
harmonic series:
Input. One positive
integer n (1 ≤ n ≤ 104).
Output. Print the sum
of the harmonic series with 4 decimal places.
Sample
input |
Sample
output |
3 |
1.8333 |
mathematics
Compute the sum of the harmonic
series using a loop.
Algorithm implementation
Read the input value of n.
scanf("%d", &n);
Compute the sum of the harmonic series.
res = 0;
for (i = 1; i <= n; i++)
res = res + 1.0 / i;
Print the answer.
printf("%.4lf\n", res);
Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new
Scanner(System.in);
int n = con.nextInt();
double res = 0;
for(int i = 1; i <= n; i++)
res = res + 1.0 / i;
System.out.println(res);
con.close();
}
}
Python implementation
Read the input value of n.
n = int(input())
Compute the sum of the harmonic series.
res = 0
for i in range(1,n+1):
res += 1 / i
Print the answer.
print(res)